package com.mass.waybill.scheduleTypes.controller;

import com.mass.core.sys.dict.model.SysDictVal;
import com.mass.core.sys.dict.service.SysDictValService;
import com.mass.core.sys.user.model.SysUser;
import com.mass.core.utils.AjaxResponse;
import com.mass.core.utils.DateUtils;
import com.mass.core.utils.ExcelUtil;
import com.mass.core.utils.NumberUtils;
import com.mass.waybill.order.model.WbShippingOrder;
import com.mass.waybill.scheduleTypes.model.WbScheduleTypes;
import com.mass.waybill.scheduleTypes.service.WbScheduleTypesService;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: ZSX
 * @Description: 费用明细
 */
@RestController
@RequestMapping("/wb/schedule/types")
public class WbScheduleTypesController {

    @Autowired(required = false)
    private WbScheduleTypesService wbScheduleTypesService;
    @Autowired
    private SysDictValService sysDictValService;

    /**export
     * 费用统计 分页
     *
     * @param wbShippingOrder
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "/costStatistics")
    public AjaxResponse costStatistics(WbShippingOrder wbShippingOrder, Integer page, Integer limit) {
        return wbScheduleTypesService.costStatistics(wbShippingOrder, page, limit);
    }

    /**
     * 导出费用统计表
     *
     * @param wbShippingOrder
     * @param response
     */
    @RequestMapping("/export")
    public void export(WbShippingOrder wbShippingOrder, Integer page, Integer limit, HttpServletResponse response) {
        //查询所有数据字典
        List<SysDictVal> sysDictValList = sysDictValService.getByTypeCode(null,null,null, null, null, null);
        //数据字典 Map  key  字典编码  value  字典值
        Map<String, String> dictMap = new HashMap<String, String>();
        for (SysDictVal sysDictVal : sysDictValList) {
            dictMap.put(sysDictVal.getValCode(), sysDictVal.getValName());
        }
        //查询应收信息
        List<WbShippingOrder> wbShippingOrderList = wbScheduleTypesService.costStatisticsAll(wbShippingOrder,page,limit);
        //表头
        String[] titles = {"序号", "订单编号", "业务员", "下单日期", "业务类型", "品名", "箱型", "箱号", "发货单位", "装货地点", "发出", "到站", "收货人", "结算人", "自运输", "司机", "车牌", "需开票", "费用类型", "应付金额", "实付金额", "收款单位"};
        if (!ObjectUtils.isEmpty(wbShippingOrder) && !ObjectUtils.isEmpty(wbShippingOrder.getStandby2()) && "2".equals(wbShippingOrder.getStandby2().trim())) {
            titles = new String[]{"序号", "订单编号", "业务员", "下单日期", "业务类型", "品名", "箱型", "箱号", "发货单位", "装货地点", "发出港", "到港", "收货人", "结算人", "自运输", "司机", "车牌", "需开票", "费用类型", "应付金额", "实付金额", "收款单位"};
        }else if(!ObjectUtils.isEmpty(wbShippingOrder) && !ObjectUtils.isEmpty(wbShippingOrder.getStandby2()) && "1".equals(wbShippingOrder.getStandby2().trim())){
            //货物运单 铁    多一个字段    到站承运
            titles = new String[]{"序号", "订单编号", "业务员", "下单日期", "业务类型", "品名", "箱型", "箱号", "发货单位", "装货地点", "发出", "到站","到站承运", "收货人", "结算人", "自运输", "司机", "车牌", "需开票", "费用类型", "应付金额", "实付金额", "收款单位"};
        }
        //文件名
        String fileName = "费用统计表";
        ServletOutputStream out = null;
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();
            int colNum = titles.length;
            int rowNO = 0;
            ExcelUtil.createExcelRow(workbook, sheet, rowNO, -1, colNum, "费用统计表");
            rowNO = rowNO + 1;
            ExcelUtil.createExcelRow(workbook, sheet, rowNO, 200, colNum, "制 表 日 期: " + (new SimpleDateFormat("yyyy-MM-dd")).format(new Date()), 180, "normal", "right");
            ++rowNO;
            ExcelUtil.createColumnHeader(workbook, sheet, rowNO, 300, titles);
            ++rowNO;
            String[][] strings = new String[wbShippingOrderList.size()][titles.length];
            //应付金额   实付金额
            Double accountsReceivableAmount = 0.00, sterilisationAmount = 0.00;
            for (int i = 0; i < wbShippingOrderList.size(); ++i) {
                WbShippingOrder order = wbShippingOrderList.get(i);
                strings[i][0] = (i + 1) + "";               //序号
                strings[i][1] = order.getOrderCode();        //订单编号
                strings[i][2] = order.getSalesman();        //业务员
                strings[i][3] = order.getOrderDate();       //下单日期
                strings[i][4] = !ObjectUtils.isEmpty(dictMap.get(order.getBusinessTypes())) ? dictMap.get(order.getBusinessTypes()) : "—";               //业务类型
                strings[i][5] = !ObjectUtils.isEmpty(dictMap.get(order.getOfTheGoods())) ? dictMap.get(order.getOfTheGoods()) : "—";               //品名
                strings[i][6] = !ObjectUtils.isEmpty(dictMap.get(order.getaBox())) ? dictMap.get(order.getaBox()) : "—"; //箱型
                strings[i][7] = !ObjectUtils.isEmpty(order.getCartonNo()) ? order.getCartonNo() : "";               //箱号
                strings[i][8] = !ObjectUtils.isEmpty(dictMap.get(order.getDeliveryUnit())) ? dictMap.get(order.getDeliveryUnit()) : "—";//发货单位
                strings[i][9] = !ObjectUtils.isEmpty(dictMap.get(order.getStandby1())) ? dictMap.get(order.getStandby1()) : "—";//装货地点
                strings[i][10] = !ObjectUtils.isEmpty(dictMap.get(order.getaStation())) ? dictMap.get(order.getaStation()) : "—";///发出
                strings[i][11] = !ObjectUtils.isEmpty(dictMap.get(order.getArriveStation())) ? dictMap.get(order.getArriveStation()) : "—"; //到站

                if(!ObjectUtils.isEmpty(wbShippingOrder) && !ObjectUtils.isEmpty(wbShippingOrder.getStandby2()) && "1".equals(wbShippingOrder.getStandby2().trim())){
                    strings[i][12] = !ObjectUtils.isEmpty(dictMap.get(order.getStandby3())) ? dictMap.get(order.getStandby3()) : "—";//到站承运

                    strings[i][13] = !ObjectUtils.isEmpty(dictMap.get(order.getReceivingUnit())) ? dictMap.get(order.getReceivingUnit()) : "—";//收货人
                    strings[i][14] = !ObjectUtils.isEmpty(dictMap.get(order.getSettlementPeople())) ? dictMap.get(order.getSettlementPeople()) : "—";//结算人
                    if (!ObjectUtils.isEmpty(order.getWhetherSelfTransport()) && order.getWhetherSelfTransport() == 1) {
                        strings[i][15] = "是";  //自运输
                    } else {
                        strings[i][15] = "否";  //自运输
                    }
                    strings[i][16] = !ObjectUtils.isEmpty(dictMap.get(order.getDriver())) ? dictMap.get(order.getDriver()) : "—";      //司机
                    strings[i][17] = !ObjectUtils.isEmpty(dictMap.get(order.getLicensePlate())) ? dictMap.get(order.getLicensePlate()) : "—";      //车牌
                    if (!ObjectUtils.isEmpty(order.getIsInvoice()) && order.getIsInvoice() == 1) {
                        strings[i][18] = "是";  //需开票
                    } else {
                        strings[i][18] = "否";  //需开票
                    }
                    if (!ObjectUtils.isEmpty(order.getWbScheduleTypes())) {
                        WbScheduleTypes wbScheduleTypes = order.getWbScheduleTypes();
                        strings[i][19] = !ObjectUtils.isEmpty(dictMap.get(wbScheduleTypes.getCostType())) ? dictMap.get(wbScheduleTypes.getCostType()) : "—";//费用类型
                        if (!ObjectUtils.isEmpty(wbScheduleTypes.getAmountPayable())) {
                            strings[i][20] = String.format("%.2f", Double.parseDouble(wbScheduleTypes.getAmountPayable().trim())); //应付金额
                            accountsReceivableAmount = NumberUtils.add(accountsReceivableAmount, Double.parseDouble(wbScheduleTypes.getAmountPayable().trim()));
                        } else {
                            strings[i][20] = "0.00"; //应付金额
                        }
                        if (!ObjectUtils.isEmpty(wbScheduleTypes.getAmountRealPay())) {
                            strings[i][21] = String.format("%.2f", Double.parseDouble(wbScheduleTypes.getAmountRealPay().trim())); //实付金额
                            sterilisationAmount = NumberUtils.add(sterilisationAmount, Double.parseDouble(wbScheduleTypes.getAmountRealPay().trim()));
                        } else {
                            strings[i][21] = "0.00"; //实付金额
                        }
                        strings[i][22] = !ObjectUtils.isEmpty(dictMap.get(wbScheduleTypes.getReceivingUnit())) ? dictMap.get(wbScheduleTypes.getReceivingUnit()) : "—"; //收款单位
                    }
                }else{
                    strings[i][12] = !ObjectUtils.isEmpty(dictMap.get(order.getReceivingUnit())) ? dictMap.get(order.getReceivingUnit()) : "—";//收货人
                    strings[i][13] = !ObjectUtils.isEmpty(dictMap.get(order.getSettlementPeople())) ? dictMap.get(order.getSettlementPeople()) : "—";//结算人
                    if (!ObjectUtils.isEmpty(order.getWhetherSelfTransport()) && order.getWhetherSelfTransport() == 1) {
                        strings[i][14] = "是";  //自运输
                    } else {
                        strings[i][14] = "否";  //自运输
                    }
                    strings[i][15] = !ObjectUtils.isEmpty(dictMap.get(order.getDriver())) ? dictMap.get(order.getDriver()) : "—";      //司机
                    strings[i][16] = !ObjectUtils.isEmpty(dictMap.get(order.getLicensePlate())) ? dictMap.get(order.getLicensePlate()) : "—";      //车牌
                    if (!ObjectUtils.isEmpty(order.getIsInvoice()) && order.getIsInvoice() == 1) {
                        strings[i][17] = "是";  //需开票
                    } else {
                        strings[i][17] = "否";  //需开票
                    }
                    if (!ObjectUtils.isEmpty(order.getWbScheduleTypes())) {
                        WbScheduleTypes wbScheduleTypes = order.getWbScheduleTypes();
                        strings[i][18] = !ObjectUtils.isEmpty(dictMap.get(wbScheduleTypes.getCostType())) ? dictMap.get(wbScheduleTypes.getCostType()) : "—";//费用类型
                        if (!ObjectUtils.isEmpty(wbScheduleTypes.getAmountPayable())) {
                            strings[i][19] = String.format("%.2f", Double.parseDouble(wbScheduleTypes.getAmountPayable().trim())); //应付金额
                            accountsReceivableAmount = NumberUtils.add(accountsReceivableAmount, Double.parseDouble(wbScheduleTypes.getAmountPayable().trim()));
                        } else {
                            strings[i][19] = "0.00"; //应付金额
                        }
                        if (!ObjectUtils.isEmpty(wbScheduleTypes.getAmountRealPay())) {
                            strings[i][20] = String.format("%.2f", Double.parseDouble(wbScheduleTypes.getAmountRealPay().trim())); //实付金额
                            sterilisationAmount = NumberUtils.add(sterilisationAmount, Double.parseDouble(wbScheduleTypes.getAmountRealPay().trim()));
                        } else {
                            strings[i][20] = "0.00"; //实付金额
                        }
                        strings[i][21] = !ObjectUtils.isEmpty(dictMap.get(wbScheduleTypes.getReceivingUnit())) ? dictMap.get(wbScheduleTypes.getReceivingUnit()) : "—"; //收款单位
                    }
                }

            }
            sheet = ExcelUtil.createColumnData(workbook, sheet, rowNO, strings, wbShippingOrderList.size() + 3);
            if(!ObjectUtils.isEmpty(wbShippingOrder) && !ObjectUtils.isEmpty(wbShippingOrder.getStandby2()) && "1".equals(wbShippingOrder.getStandby2().trim())){
                //最后一行
                HSSFRow lastRow = sheet.createRow((short) (sheet.getLastRowNum() + 1));
                lastRow.createCell(1).setCellValue(new HSSFRichTextString("合计："));
                lastRow.createCell(20).setCellValue(new HSSFRichTextString(String.format("%.2f", accountsReceivableAmount)));
                lastRow.createCell(21).setCellValue(new HSSFRichTextString(String.format("%.2f", sterilisationAmount)));
            }else {
                //最后一行
                HSSFRow lastRow = sheet.createRow((short) (sheet.getLastRowNum() + 1));
                lastRow.createCell(1).setCellValue(new HSSFRichTextString("合计："));
                lastRow.createCell(19).setCellValue(new HSSFRichTextString(String.format("%.2f", accountsReceivableAmount)));
                lastRow.createCell(20).setCellValue(new HSSFRichTextString(String.format("%.2f", sterilisationAmount)));
            }
            // ExcelUtil.createSummaryRow(workbook, sheet, colNum, "行数合计：" + strings.length, 180, "normal", "right");

            fileName = fileName + (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());
            out = response.getOutputStream();
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xls");
            workbook.write(out);
        } catch (
                Exception var35) {
            var35.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException var34) {
                var34.printStackTrace();
            }

        }

    }

    /**
     * 条件查询
     *
     * @param wbScheduleTypes
     * @return
     */
    @GetMapping(value = "/wbScheduleTypes")
    public AjaxResponse findConditions(WbScheduleTypes wbScheduleTypes) {
        return AjaxResponse.success(wbScheduleTypesService.findConditions(wbScheduleTypes));
    }

    /**
     * 增补
     *
     * @param wbScheduleTypesList
     * @return
     */
    @PostMapping("/supplement")
    public AjaxResponse supplement(@RequestBody List<WbScheduleTypes> wbScheduleTypesList, HttpSession session) {
        String orderCode = "", batchNumber = "";
        Object object = session.getAttribute("sysUser");
        if (!ObjectUtils.isEmpty(object)) {
            SysUser sysUser = (SysUser) object;
            if (!ObjectUtils.isEmpty(wbScheduleTypesList)) {
                for (WbScheduleTypes wbScheduleTypes : wbScheduleTypesList) {
                    orderCode = wbScheduleTypes.getOrderCode();
                    batchNumber = wbScheduleTypes.getBatchNumber();
                    wbScheduleTypes.setStates(1);
                    wbScheduleTypes.setSupplementaryApplicationTime(DateUtils.getDate("yyyy年MM月dd日 HH:mm"));
                    wbScheduleTypes.setSupplementaryApplicant(sysUser.getName());
                }
            }
        } else {
            return AjaxResponse.success("未登录！");
        }
        return AjaxResponse.success(wbScheduleTypesService.replaceData(wbScheduleTypesList, 1, orderCode, batchNumber));
    }

    /**
     * 增补审核
     *
     * @param wbScheduleTypes
     * @param reviewStatus    审核状态 1 审核通过 2 审核不通过
     * @param session
     * @return
     */
    @PostMapping("/supplementaryAudit")
    public AjaxResponse supplementaryAudit(WbScheduleTypes wbScheduleTypes, HttpSession session) {
        Object object = session.getAttribute("sysUser");
        if (!ObjectUtils.isEmpty(object)) {
            SysUser sysUser = (SysUser) object;
            if (!ObjectUtils.isEmpty(wbScheduleTypes) && !ObjectUtils.isEmpty(wbScheduleTypes.getReviewStatus()) && wbScheduleTypes.getReviewStatus() != 0) {//审核
                if (wbScheduleTypes.getReviewStatus() == 1) {
                    wbScheduleTypes.setStates(0);
                } else {
                    wbScheduleTypes.setStates(1);
                }
                wbScheduleTypes.setSupplementaryAuditTime(DateUtils.getDate("yyyy年MM月dd日 HH:mm"));
                wbScheduleTypes.setAdditionalAuditor(sysUser.getName());
            }
        } else {
            return AjaxResponse.success("未登录！");
        }
        return AjaxResponse.success(wbScheduleTypesService.supplementaryAudit(wbScheduleTypes));
    }

    /**
     * 分页条件查询增补信息
     *
     * @param wbShippingOrder
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/findSupplement")
    public AjaxResponse findSupplement(WbShippingOrder wbShippingOrder, Integer page, Integer limit) {
        return wbScheduleTypesService.findSupplement(wbShippingOrder, page, limit);
    }

    /**
     * 删除增补单
     *
     * @param batchNumber 编号
     * @return
     */
    @RequestMapping("/deleteSupplement")
    public AjaxResponse deleteSupplement(String batchNumber) {
        return AjaxResponse.success(wbScheduleTypesService.deleteSupplement(batchNumber));
    }
}
